package org.skyui.jpa;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Persistence;

import org.skyui.beans.AbstractBean;
import org.skyui.beans.OrganizationBean;


public class JPAManager {

	protected static String PERSISTENCE_UNIT_NAME="skycommand";

	private static EntityManager manager = null;

	public static synchronized EntityManager getManager() {
		if (manager == null)
			manager = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME)
			.createEntityManager();
		return manager;
	}
	
	
	
	public static void persist(AbstractBean bean) {

		getManager().getTransaction().begin();
		if (bean.getOrganization() == null) {
			throw new RuntimeException("Null organization");
		}
		getManager().persist(bean);
		getManager().getTransaction().commit();
	}

	private static List query(String q) {
		return getManager().createQuery(q).getResultList();
	}

	public static void remove(Object bean) {
	
		getManager().getTransaction().begin();
		getManager().remove(bean);
		getManager().getTransaction().commit();
	}

	public static void removeManyToManyRelation(AbstractBean bean1, AbstractBean bean2) {
		getManager().getTransaction().begin();
		bean1.removeBeanRelation(bean2);
		bean2.removeBeanRelation(bean1);
		getManager().persist(bean1);
		getManager().persist(bean2);
		getManager().getTransaction().commit();
	}

	public static void addManyToManyRelation(AbstractBean bean1, AbstractBean bean2) {
		getManager().getTransaction().begin();
		bean1.addBeanRelation(bean2);
		bean2.addBeanRelation(bean1);
		getManager().persist(bean1);
		getManager().persist(bean2);
		getManager().getTransaction().commit();		
	}

	public static void refresh(AbstractBean bean) {
		if (bean.isTemplate())
			return;
		getManager().getTransaction().begin();
		getManager().refresh(bean);
		getManager().getTransaction().commit();
	}

	public static List readGlobalBeansFromStorage(Class beanClass) {
		return query("SELECT e FROM " + beanClass.getSimpleName() + " e");
	}

	public static List readGlobalBeansFromStorageWhereString(Class beanClass,
			String field, String value) {
				return query("SELECT e FROM " + beanClass.getSimpleName()
						+ " e WHERE e." + field + " = " + "'" + value + "'");
			}

	public static List readBeansFromStorage(Class beanClass, OrganizationBean organization) {
		if (organization == null)
			return readGlobalBeansFromStorage(beanClass);
	
		return readGlobalBeansFromStorageWhereString(beanClass,
				"organization.id", organization.getId());
	}

	public JPAManager() {
		super();
	}
	
	public static void init(String persistentUnit) {
		PERSISTENCE_UNIT_NAME = persistentUnit;
		getManager();
	}
	
	

}